package com.s7.compat.status.utils;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

public class NavigationUtils {

    public static void assistActivity(View viewObserving) {
        new NavigationUtils(viewObserving, null);
    }

    public static void assistActivity(View viewObserving, Activity context) {
        new NavigationUtils(viewObserving, context);
    }

    private View mViewObserved;
    private static Activity context;
    private int usableHeightPrevious;
    private ViewGroup.LayoutParams frameLayoutParams;

    private NavigationUtils(View viewObserving, Activity context) {
        mViewObserved = viewObserving;
        this.context = context;
        mViewObserved.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                resetLayoutByUsableHeight(computeUsableHeight());
            }
        });
        frameLayoutParams = mViewObserved.getLayoutParams();
    }

    private void resetLayoutByUsableHeight(int usableHeightNow) {
        if (usableHeightNow != usableHeightPrevious) {
            frameLayoutParams.height = usableHeightNow;
            mViewObserved.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mViewObserved.getWindowVisibleDisplayFrame(r);
        if (context != null) {
            return (r.bottom - r.top) + StatusBarUtils.getInstance(context).getStatusBarHeight();
        }
        return (r.bottom - r.top);
    }
}